#-*-encoding: utf-8 -*-
import wsgiref.handlers
import cgi,os

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import images
from google.appengine.ext.webapp import template
from trendy import Topic, Comparison

gadskel = r'''<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="trendy" height ="280">
    <Require feature="dynamic-height" />
    <Require feature="locked-domain" />
    <Require feature="wave-preview" />
</ModulePrefs>
<Content type="html">
<![CDATA[
<iframe src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/trends_gadget.xml&amp;source=imag&amp;up_is_init=true&amp;up_cur_term=%s&amp;up_date=mtd&amp;up_region=US" style="border:1px solid #ccc; padding:10px;" width="330" height="250" frameborder="0" scrolling="no"></iframe>
]]>
</Content>
</Module>
'''
gadskeltest = r'''<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="trendy" height="260">
    <Require feature="dynamic-height" />
    <Require feature="locked-domain" />
    <Require feature="wave-preview" />
</ModulePrefs>
<Content type="html">
<![CDATA[
Hello!
]]>
</Content>
</Module>
'''
class Home(webapp.RequestHandler):
    def get(self):
        top10q = Topic.all().order('-frequency')
        self.top10 = top10q.fetch(10)
        rede = self.cria_rede()
        template_values = {'top10':self.top10,'rede':rede}
        path = os.path.join(os.path.dirname(__file__), 'Home.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        pass
    
    def cria_rede(self):
        '''
        cria a rede no formato json para a visualização
        '''
        q2 = Comparison.all()
        for t in self.top10:
            q3 = q2.filter('topics = ',t)
            
        ln = ['{nodeName:"%s", group:%s}'%(i.topic,i.frequency) for i in self.top10]
        ln = ','.join(ln)
        le = ''
        rede = '{nodes:[%s],edges:[%s]}'%(ln,le)
        return rede
        
class TrendGadget(webapp.RequestHandler):
    def get(self):
        if self.request.get('markup') == "":
            contents = gadskel%"linux,windows7"
        else:
            contents = gadskel%self.request.get('markup')
        self.response.headers['Content-Type'] = 'text/xml'
        self.response.out.write(contents)
    

def main():
    application = webapp.WSGIApplication(
                                        [('/', Home),
                                        ('/gadget.xml', TrendGadget),
                                        ],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
